package integral

import (
	"context"
	"fmt"
	"github.com/shopspring/decimal"
	"private-domain-overseas-service/admin/business/api/internal/repository/integral"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type IntegralGoodsEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 创建积分商城商品
func NewIntegralGoodsEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralGoodsEditLogic {
	return &IntegralGoodsEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *IntegralGoodsEditLogic) IntegralGoodsEdit(req *types.IntegralGoodsEditRequest) error {
	goodsDao := integral.NewIntegralGoodsDao(l.ctx, l.svcCtx)

	//定义换算单位变量
	baiDecimal := decimal.NewFromInt(100)
	//获取值
	goodsPriceDecimal, _ := decimal.NewFromString(req.GoodsPrice)
	//元转分
	goodsPriceFenDecimal := goodsPriceDecimal.Mul(baiDecimal)
	//获取当前时间戳
	nowUnix := time.Now().Unix()

	//组装参数
	goodsInfo := &ent.HzIntegralGoods{
		GoodsImage:      req.GoodsImage,
		GoodsSmallImage: req.GoodsSmallImage,
		GoodsInfo:       req.GoodsInfo,
		GoodsPrice:      goodsPriceFenDecimal.IntPart(),
		GoodsSort:       req.Sort,
		GoodsStatus:     req.Status,
		UpdateAt:        nowUnix,
	}

	//编辑
	if req.Type == "edit" {
		goodsInfo.ID = int(req.Id)
		err := goodsDao.IntegralGoodsUpdate(goodsInfo, nil)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("编辑商品信息失败：: %v", err))
		}
	}

	//添加
	if req.Type == "add" {
		goodsInfo.CreatedAt = nowUnix
		err := goodsDao.IntegralGoodsCreate(goodsInfo, nil)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("添加商品信息失败：: %v", err))
		}
	}

	return nil
}
